<?php
/**
 * 支付相关接口
 * */

namespace App\Http\Controllers;

use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Model\SystemConfig;
use App\Http\Services\FinancePayServices;
use App\Http\Services\FinanceRechargeOrderServices;
use App\Http\Services\FinanceWithdrawServices;
use App\Http\Services\MsgServices;
use App\Http\Services\UserServices;
use App\Lib\Pay\Applepay\ApplePayResults;
use App\Lib\Response;
use Illuminate\Http\Request;
use App\Http\Services\FinanceWithdrawNewServices;

class FinanceWithdrawController extends Controller
{

    private $request;
    private $service_withdraw;
    private $service_msg;
    private $user_services;
    private $withdrawNewService;

    public function __construct(Request $request, FinanceWithdrawServices $financeWithdrawServices)
    {
        $this->request = $request;
        $this->service_withdraw = $financeWithdrawServices;
        $this->service_msg = new MsgServices();
        $this->user_services = new UserServices();
        $this->withdrawNewService = new FinanceWithdrawNewServices();
    }

    //驳回提现
    public function dismiss(){
        $order_sn = $this->request->get("order_sn");
        if (empty($order_sn)){
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
            return ;
        }
        $ret = $this->service_withdraw->dismiss_order($order_sn);
        if ($ret == Hint::ERROR){
            OutJson::outJsonNoData(Hint::ERROR);
            return ;
        }
        if ($ret == Hint::FINANCE_ORDER_COMPLETE){
            OutJson::outJsonNoData(Hint::FINANCE_ORDER_COMPLETE);
            return ;
        }
        OutJson::outJsonNoData(Hint::SUCCESS);
    }

    /**
     * 下单成功 回调方法
     * */
    public function cloudCountNotify(){
        $params = $this->request->post();

        $rest = $this->service_withdraw->cloudCountNotify($params);

        write_log('applyWithdraw-cloudAccount','cloudCountNotify-云账户回调', $rest);

        if($rest['code'] == 0){
            $data = $rest['data']['orderData'] ?? [];
            if(isset($data['user_id']) && isset($data['price'])){
                $this->service_msg->send_sys_text_msg($data['user_id'],"提现申请通过！您已成功提现".($data['price']/100)."元");
            }
            echo 'success';
        }else{
            echo 'fail';
        }
    }

    /**
     * 下单成功 回调方法
     * */
    public function cloudCountNotifyLarge(){
        $params = $this->request->post();
        $rest = $this->service_withdraw->cloudCountNotify($params, 2);

        write_log('applyWithdraw-cloudAccount','cloudCountNotify-大额云账户回调', $rest);

        if($rest['code'] == 0){
            $data = $rest['data']['orderData'] ?? [];
            if(isset($data['user_id']) && isset($data['price'])){
                $this->service_msg->send_sys_text_msg($data['user_id'],"提现申请通过！您已成功提现".($data['price']/100)."元");
            }
            echo 'success';
        }else{
            echo 'fail';
        }
    }

    // ########## START 提现规则限制 全局设定 ########################################
    /**
     * 响应数据
     * */
    public function responseData($response = true){
        $this->service_withdraw->set_cross();

        $params = $this->request->post();

        // 取出调用方法名
        $action = explode('@', $this->request->route()[1]['uses'])[1];

        $result = $this->service_withdraw->$action($params);

        write_log('withdrawLimit', $action, ['params' => $params, 'result' => $result]);

        if ($response) {
            OutJson::outJsonResult($result['code'], $result['data']);
        } else {
            return json_encode($result, JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 提现现金次数
     * */
    public function withdrawCashNumber(){
        return $this->responseData();
    }

    /**
     * 提现银行卡张数
     * */
    public function withdrawBankNumber(){
        return $this->responseData();
    }

    /**
     * 提现周期
     * */
    public function withdrawWeek(){
        return $this->responseData();
    }

    /**
     * 提现例外用户
     * */
    public function withdrawExceptionUser(){
        return $this->responseData();
    }

    /**
     * 查看提现记录
     */
    public function getWithdrawLog(){
        init_redis_session();

        $params = $this->request->all();
        $rest = $this->service_withdraw->getWithdrawLog($params);
        Response::returnResult($rest['code'], $rest['data']);
    }

    /**
     * 查看提现进度
     */
    public function getWithdrawProcess(){
        init_redis_session();

        $params = $this->request->post();
        $rest = $this->service_withdraw->getWithdrawProcess($params);
        Response::returnResult($rest['code'], $rest['data']);
    }

    /**
     * 撤回提现
     */
    public function recallWithdraw(){
        init_redis_session();

        $params = $this->request->post();
        $rest = $this->service_withdraw->recallWithdraw($params);
        Response::returnResult($rest['code'], $rest['data']);
    }

    /**
     * 获取注册个体账户url
     */
    public function getCloudH5Url(){
        $params = $this->request->post();
        $user_id = $params['user_id'];
        if(empty($user_id)){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $data = $this->service_withdraw->getCloudH5Url($user_id);
        if($data == Hint::ERR_DATA_NOT_EXIST){
            Response::returnResult(Hint::ERR_DATA_NOT_EXIST);
        }
        if($data == Hint::ERR_DATA_EXIST){
            Response::returnResult(Hint::ERR_DATA_EXIST);
        }
        Response::returnResult(Hint::SUCCESS ,$data);
    }
    /**
     * 个体工商户注册回调
     */
    public function cloudH5Notify()
    {
        $params = $this->request->post();
        write_log('applyWithdraw-cloudAccount','cloudH5Notify', $params);
        $rest = $this->service_withdraw->cloudH5Notify($params);
        if ($rest['code'] == 0) {
            echo 'success';
        }else{
            echo 'fail';
        }
    }

    public function updateOrderStatus(){
        $params = $this->request->post();
        if(empty($params['order_sn']) || empty($params['status'])){
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
        }
//        if($params['status'] == 1 && empty($params['voucher'])){
//            OutJson::outJsonNoData(Hint::PARAM_ERROR);
//        }
        $res = $this->service_withdraw->updateOrderStatus($params);
        if($res == Hint::ERR_DATA_NOT_EXIST){
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
        }
        if($res == Hint::NOT_ALLOWED){
            OutJson::outJsonNoData(Hint::NOT_ALLOWED);
        }
        if($res == Hint::AUTH_ERROR){
            OutJson::outJsonNoData(Hint::AUTH_ERROR);
        }
        OutJson::outJsonNoData(Hint::SUCCESS);
    }

    /**
     * @desc 获取用户是否可以提现打款
     */
    public function getIsAllowWithdraw()
    {
        $code = $this->service_withdraw->isAllowWithDraw($this->request->all());
        Response::returnResult($code);

    }

    public function updatePayType(){
        $params = $this->request->post();
        if(empty($params['order_sn']) || empty($params['pay_type'])){
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
        }
        $res = $this->service_withdraw->updatePayType($params);
        if($res == Hint::ERR_DATA_NOT_EXIST){
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
        }
        if($res == Hint::AUTH_ERROR){
            OutJson::outJsonNoData(Hint::AUTH_ERROR);
        }
        OutJson::outJsonNoData(Hint::SUCCESS);
    }
    // ########## END   ###########################################################

    /**
     * 查看提现记录
     */
    public function getWithdrawLogV2(Request $request){
        $userInfo = $this->user_services->get_current_user();
        if(empty($userInfo['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $page = (int) $request->get('page', 0);
        $pageSize = (int) $request->get('pageSize', 20);

        $rest = $this->service_withdraw->getWithdrawLogV2($userInfo['user_id'], $page, $pageSize);
        Response::returnResult($rest['code'], $rest['data']);
    }

    /**
     * 是否可以提现
     * */
    public function checkWithdraw(){
        $userInfo = $this->user_services->get_current_user();
        if(empty($userInfo['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }

        $rest = $this->service_withdraw->checkWithdraw($userInfo['user_id']);
        if($rest['code'] != Hint::SUCCESS) {
            Response::returnResult($rest['code'], [], $rest['msg']);
        }
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * app 申请提现
     * */
    public function applyWithdrawV2(Request $request){
        $userInfo = $this->user_services->get_current_user();
        if(empty($userInfo['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $bankId = (int) $request->input('bankId');
        $price = (int) $request->input('price');
        $payType = (int) $request->input('pay_type', 7);
        if(empty($bankId)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if($price < 100) {
            Response::returnResult(Hint::PARAM_ERROR, [], '提现金额需满100');
        }
        if(!($price%10==0)) {
            Response::returnResult(Hint::PARAM_ERROR, [], '每次提现须为10的倍数');
        }

        //提现限制
        $transfer_diamond_max = (new SystemConfig())->getKeyConfig('tx_max')[0];
//        dd($transfer_diamond_max);
        if ($transfer_diamond_max && $transfer_diamond_max < $price) {
            Response::returnResult(Hint::PARAM_ERROR, [], '提现数量不可大于' . $transfer_diamond_max);
        }


        //账号类型 7=银行卡-贝灵斯 8=支付宝-慧用工 9=支付宝-提现
        if($payType < 7) $payType = 7;//兼容旧代码
        if(!in_array($payType, [7,8,9])) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if($payType == 8) $payType = 9;//慧用工变成支付宝

        $rest = $this->service_withdraw->applyWithdrawV2($userInfo['user_id'], $bankId, $price, $payType);
        if($rest['code'] != Hint::SUCCESS) {
            $msg = empty($rest['data']['error_msg']) ? "" : $rest['data']['error_msg'];
            Response::returnResult($rest['code'], [], $msg);
        }
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 后台审核同意贝灵斯提现操作
     * */
    public function payBlsOrder(Request $request){
        $orderSn = (string) $request->get('order_sn');
        if(empty($orderSn)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $rest = $this->service_withdraw->payBlsOrder($orderSn);
        if($rest['code'] != Hint::SUCCESS) {
            Response::returnResult($rest['code'], [], $rest['msg']);
        }

        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 提现回调 贝灵斯
     * */
    public function blsNotify(){
        $str = 'fail';
        do {
            $params = $this->request->post();
            $sign = isset($_SERVER['HTTP_X_YZX_SIGNATURE']) ? $_SERVER['HTTP_X_YZX_SIGNATURE']:'';
            write_log('applyWithdraw-bls','blsNotify', ['post'=>$params,'HTTP_X_YZX_SIGNATURE'=>$sign]);

            if(empty($sign)) {
                break;
            }
            if(empty($params['data'])) {
                break;
            }
            //验签
            $check = $this->service_withdraw->checkBlsSign($sign, $params['data']);
            if(!$check) {
                break;
            }

            $data = json_decode($params['data'], true);
            if(empty($data['state']) || empty($data['batchNo']) || empty($data['custOrderNo']) || empty($data['orderNo'])) {
                break;
            }
            //6失败 7成功
            if($data['state'] == 6 || $data['state'] == 7) {
                $res = $this->service_withdraw->blsNotify($data);
                if($res['code'] != Hint::SUCCESS) {
                    write_log('applyWithdraw-bls','blsNotify error', ['post'=>$params,'HTTP_X_YZX_SIGNATURE'=>$sign, 'res'=>$res]);
                }
            }

            $str = 'success';
        } while (false);

        $sign = $this->service_withdraw->getBlsSign($str);
        header('X-Yzx-Signature:'.$sign);
        echo $str;
    }

    /**
     * 获取用户提现支付宝信息
     */
    public function getUserAlipay(Request $request)
    {
        $userInfo = $this->user_services->get_current_user();
        if(empty($userInfo['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }

        $res = $this->withdrawNewService->getUserAlipay($userInfo['user_id']);

        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    /**
     * 用户提现支付宝保存
     */
    public function saveUserAlipay(Request $request)
    {
        $userInfo = $this->user_services->get_current_user();
        $userAgent = $request->userAgent();
        if(empty($userInfo['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $workerAccount = trim($request->input('worker_account'));//支付宝账号
        if(empty($workerAccount) && !is_numeric($workerAccount)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $bank_code = trim($request->input('bank_code'));//银行账号
        $bank_source = trim($request->input('bank_source'));//银行开户

        $userAgent = explode(';',$userAgent);
        $version = $userAgent[1];
        if($version >= '1.0.1'){
            if(empty($bank_source) || empty($bank_code)) {
                Response::returnResult(Hint::PARAM_ERROR);
            }

            if(!is_numeric($bank_code)){
                Response::returnResult(Hint::ERR_NORMAL,[],'卡号不正确');
            }
        }
        $res = $this->withdrawNewService->saveUserAlipay($userInfo['user_id'], $userInfo['phone'], $workerAccount, $bank_code, $bank_source);

        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    /**
     * 用户提现支付宝删除
     */
    public function delUserAlipay(Request $request)
    {
        $userInfo = $this->user_services->get_current_user();
        if(empty($userInfo['user_id'])) {
            Response::returnResult(Hint::LOGIN_OUT);
        }

        $res = $this->withdrawNewService->delUserAlipay($userInfo['user_id']);

        Response::returnResult($res['code'], $res['data'], $res['msg']);
    }

    /**
     * 提现回调 慧用工
     * */
    public function yuqueNotify(Request $request){
        $data = ['statusCode' => '000000', 'statusText' => ''];

        do {
            $params = $request->post();
            write_log('yuque', 'yuqueNotify', ['params'=>$params]);
            //余额不足
            // $json = '{"params":{"cooperatorId":"C1181272787789029376","businessBody":"E1D0643865A1A00E5791BBBB8DD89FCB3E4511B77B450F535A74AB4293DED81AAF632468C9F899A5C98C2B04BB6AD9B5534624228488E56CA05ED3D71FBB45229ACB633AD124F2E50557B90EAB1C7692574FA57B0BAA287FF62B09C7CF5C4F573A62B86F3F9C8B31B29EA345F7853CBA8F8E015E83083BA52137D62A88165B703A731A0B3ECC054D417D52AD0AA1BFD6999FFA352E1886EB89BA22DFEB8D22F9F089CC540F494DA11D4F3A7794441148E70997B0A607435B98C845B2954AE82399187CB905C43F95DFDD6919CFC6A84E06A544313E9FF81CF6C4BEEE75262050"}}';
            //[支付宝开放平台]收款账号不存在或姓名有误，建议核实账号和姓名是否准确
            // $json = '{"params":{"cooperatorId":"C1181272787789029376","businessBody":"E1D0643865A1A00E5791BBBB8DD89FCB3E4511B77B450F535A74AB4293DED81AA8B0B07DDF3CE5B87130C2CA1C4E6731E489B227D36E4124F8415E9690DC75649ACB633AD124F2E50557B90EAB1C7692DD640E1920E855DDA9B472E218E523643B9BA782494C4374244198B7452FC96C0739206A4DA588478D20A8040B4F8D36447523ED249A1AB04396CE7FD8200952A19E519831665B8A5A2241F552CEFF924047D312BD1EC1F1516E08EA53590AD4C49021268F9D0C23F0CB39983C0F8A671CACA72CA708B6B7A0D144A2BB3CE3A7101F532662FD91779C974493BE28A80D9B1A05E6AA2BF81153C6363E8B55BB8C562010585DDDBD9658D1936143695E1836F331FF7470791B39AD455053FA481CD6F9A6FDF522BFAC94C3EF3461AF8C9D93538852ED08B9F2DBD1269B7140F49E"}}';
            //成功
            // $json = '{"params":{"cooperatorId":"C1181272787789029376","businessBody":"E1D0643865A1A00E5791BBBB8DD89FCB6DC6398EBB56D46A9AB46340B4F191E9AE4CBD3C21719F6A6B1C3642E73243BA6920241C4E1937994E42CFCF25386CD72D3BFFFE6267870CA59B0EF139D6FD659100550948EF0BF888DCCC40FCF438825F1E25B756C35F4A64F68D48198A4C2C04AD4C53944C4BB25BEF1D7B216882B50959A37950E957552BFC53288DCEA89B9FB008547655A2EDC7528DDEFBE3093F10BE47318C56414859D65D86D0695B46E7436325980392F52B309187A27460EDBDD099AF6AFA85E7DF204BFD7FC243B378C7B5A85A7D0C41BF7F8EEC958C09F0A408D472ED7B09404765D298F02146F6"}}';
            // $params = json_decode($json, true);
            // $params = $params['params'];
            if(empty($params['cooperatorId'])) {
                break;
            }
            if(empty($params['businessBody'])) {
                break;
            }
            //处理
            $res = $this->withdrawNewService->yuqueNotify($params['cooperatorId'], $params['businessBody']);
            if($res['code'] != Hint::SUCCESS) {
                $data = ['statusCode' => $res['code'], 'statusText' => $res['msg']];
            }
        } while (false);

        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 提现回调 支付宝
     * */
    public function alipayNotify(Request $request){
        $res = 'fail';

        do {
            $params = $request->post();
            write_log('alipay', 'alipayNotify', ['params'=>$params]);
            //校验
            if(empty($params['biz_content'])) {
                break;
            }
            $params = $params['biz_content'];
            $params = json_decode($params, true);
            if(empty($params['out_biz_no']) || empty($params['order_id'])) {
                break;
            }

            //处理
            $res = $this->withdrawNewService->alipayNotify($params);

            $res = 'success';
        } while (false);

        echo $res;
    }

}
